﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
using NHibernate.Criterion;
using System.Reflection;

namespace ZDSoft.QLMS.Entity
{
    public class EntityBase<T> : ActiveRecordBase
    {
        #region 公共属性

        //编号
        [PrimaryKey("ID")]
        public int ID { get; set; }

        #endregion

        #region 公共方法



        //查询所有
        public IList<T> FindAll()
        {
            return ActiveRecordBase.FindAll(typeof(T)) as IList<T>;
        }

        //通过ID查找实体
        public T FindByID(int id)
        {
            return (T)ActiveRecordBase.FindByPrimaryKey(typeof(T), id);
        }

        //创建
        public void Create(T t)
        {
            ActiveRecordBase.Create(t);
        }

        //修改
        public void Edit(T t)
        {
            ActiveRecordBase.Update(t);
        }

        //删除
        public void Delete(int id)
        {
            ActiveRecordBase.Delete(FindByID(id));
        }

        /// <summary>
        /// 分页获取对象集合
        /// </summary>
        /// <param name="queryConditions">查询条件，可以是多个,形式如："UserName"="Michael"</param>
        /// <param name="orderList">排序方式，根据字段排序，形式如："UserName","DESC"</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <param name="count">满足条件的记录总数</param>
        /// <returns>返回满足条件的实体集合</returns>
        public IList<T> GetPaged(IList<ICriterion> queryConditions, IList<Order> orderList, int pageIndex,
            int pageSize, out int count)
        {
            if (queryConditions == null)//如果为null则赋值为一个总数为0的集合
            {
                queryConditions = new List<ICriterion>();//为了满足ActiveRecordBase.SlicedFindAll方法，即查询条件不能为null
            }
            if (orderList == null)//如果为null则赋值为一个总数为0的集合
            {
                orderList = new List<Order>();//为了满足ActiveRecordBase.SlicedFindAll方法，即排序条件不能为null
            }
            count = ActiveRecordBase.Count(typeof(T), queryConditions.ToArray());//根据查询条件获取满足条件的对象总数
            Array arr = ActiveRecordBase.SlicedFindAll(typeof(T), (pageIndex - 1) * pageSize, pageSize, orderList.ToArray(), queryConditions.ToArray());//根据查询条件分页获取对象集合
            return arr as IList<T>;
        }

        /// <summary>
        /// 根据查询条件获取所有满足条件的实体
        /// </summary>
        /// <param name="queryConditions">查询条件，可以是多个,形式如："UserName"="Michael"</param>
        /// <returns>返回满足条件的实体集合</returns>
        public IList<T> Find(IList<ICriterion> queryConditions)
        {
            Array arr = ActiveRecordBase.FindAll(typeof(T), queryConditions.ToArray());
            return arr as IList<T>;
        }
        #endregion
    }
}
